package com.zycfc.zsf.boot.util.sftp;

import com.jcraft.jsch.*;
import java.io.*;
import com.zycfc.zsf.boot.util.collection.*;
import org.slf4j.*;
import java.util.*;

public class SftpUtil
{
    private static final Logger log;
    private String ip;
    private String username;
    private String password;
    private int port;
    private ChannelSftp sftpChannel;
    private Session session;
    
    public SftpUtil(final String serverIP, final int port, final String username, final String password) {
        this.ip = "";
        this.username = "";
        this.password = "";
        this.port = -1;
        this.sftpChannel = null;
        this.session = null;
        this.ip = serverIP;
        this.port = port;
        this.username = username;
        this.password = password;
        SftpUtil.log.info("\u521d\u59cb\u5316sftp:{},{},{},{}", new Object[] { serverIP, port, username, password });
    }
    
    public SftpUtil(final String serverIP, final int port, final String username) {
        this.ip = "";
        this.username = "";
        this.password = "";
        this.port = -1;
        this.sftpChannel = null;
        this.session = null;
        this.ip = serverIP;
        this.port = port;
        this.username = username;
        this.password = this.password;
        SftpUtil.log.info("\u521d\u59cb\u5316sftp:{},{},{},{}", new Object[] { serverIP, port, username });
    }
    
    public boolean connectServer() {
        boolean retflag = false;
        try {
            final JSch jsch = new JSch();
            this.session = jsch.getSession(this.username, this.ip, this.port);
            if (this.password != null) {
                this.session.setPassword(this.password);
            }
            final Properties config = new Properties();
            ((Hashtable<String, String>)config).put("StrictHostKeyChecking", "no");
            this.session.setConfig(config);
            this.session.connect();
            (this.sftpChannel = (ChannelSftp)this.session.openChannel("sftp")).connect();
            retflag = true;
            SftpUtil.log.info("sftp:{},{},{},{}\u8fde\u63a5\u6210\u529f", new Object[] { this.ip, this.port, this.username, this.password });
        }
        catch (JSchException e) {
            SftpUtil.log.error("\u8fde\u63a5sftp:{},{}\u5931\u8d25,", new Object[] { this.ip, this.username, e });
        }
        return retflag;
    }
    
    public boolean connectServer(final String filePath, final String passphrase) {
        boolean retflag = false;
        try {
            final JSch jsch = new JSch();
            jsch.addIdentity(filePath);
            this.session = jsch.getSession(this.username, this.ip, this.port);
            final Properties config = new Properties();
            ((Hashtable<String, String>)config).put("StrictHostKeyChecking", "no");
            this.session.setConfig(config);
            if (passphrase != null && !"".equals(passphrase)) {
                final UserInfo ui = (UserInfo)new MyUserInfo(passphrase);
                this.session.setUserInfo(ui);
            }
            this.session.connect();
            (this.sftpChannel = (ChannelSftp)this.session.openChannel("sftp")).connect();
            retflag = true;
            SftpUtil.log.info("sftp:{},{},{},{}\u8fde\u63a5\u6210\u529f", new Object[] { this.ip, this.port, this.username, filePath });
        }
        catch (JSchException e) {
            SftpUtil.log.error("\u8fde\u63a5sftp:{},{}\u5931\u8d25,", new Object[] { this.ip, this.username, e });
        }
        return retflag;
    }
    
    public boolean isExists(final String directory) {
        boolean retflag = false;
        try {
            this.sftpChannel.cd(directory);
            retflag = true;
        }
        catch (SftpException e) {
            SftpUtil.log.error("\u5224\u65ad\u76ee\u6807\u670d\u52a1\u5668\u4e0a\u6587\u4ef6\u8def\u5f84\u662f\u5426\u5b58\u5728\u5931\u8d25,", (Throwable)e);
        }
        return retflag;
    }
    
    public List<String> getFileList(final String directory) {
        List<String> fileNames = null;
        if (!this.isExists(directory)) {
            return fileNames;
        }
        try {
            final Vector<String> files = (Vector<String>)this.sftpChannel.ls(this.sftpChannel.pwd());
            fileNames = new ArrayList<String>();
            for (int i = 0; i < files.size(); ++i) {
                final Object obj = files.elementAt(i);
                if (obj instanceof ChannelSftp.LsEntry) {
                    final ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)obj;
                    if (!entry.getAttrs().isDir()) {
                        fileNames.add(entry.getFilename());
                    }
                }
            }
        }
        catch (SftpException e) {
            SftpUtil.log.error("\u83b7\u53d6\u76ee\u6807\u670d\u52a1\u5668\u4e0a\u76ee\u5f55\u4e0b\u6587\u4ef6\u5217\u8868\u5931\u8d25,", (Throwable)e);
        }
        return fileNames;
    }
    
    public boolean mkdirs(String directory) {
        boolean retflag = false;
        if (this.sftpChannel == null) {
            return retflag;
        }
        if (directory == null) {
            return retflag;
        }
        directory = directory.replace("\\", "/");
        final String[] dir = directory.split("/");
        String headpath = "";
        try {
            for (int i = 0; i < dir.length; ++i) {
                final String path = dir[i];
                if (path != null) {
                    if (!"".equals(path)) {
                        if (!this.isExists(headpath + "/" + path)) {
                            this.sftpChannel.mkdir(headpath + "/" + path);
                        }
                        headpath = headpath + "/" + path;
                    }
                }
            }
            retflag = true;
        }
        catch (SftpException e) {
            SftpUtil.log.error("\u8fdc\u7a0b\u521b\u5efa\u76ee\u5f55\u5931\u8d25,", (Throwable)e);
        }
        return retflag;
    }
    
    public boolean upload(final String remoteDirectory, final String localFilePath, final String fileNewName) {
        boolean retflag = false;
        if (this.sftpChannel == null) {
            SftpUtil.log.error("\u4e0a\u4f20\u6587\u4ef6{}\u81f3\u76ee\u5f55{}\u5931\u8d25\uff0c\u672a\u6253\u5f00sftp", (Object)localFilePath, (Object)remoteDirectory);
            return retflag;
        }
        InputStream fileinputstream = null;
        try {
            this.mkdirs(remoteDirectory);
            this.sftpChannel.cd(remoteDirectory);
            final File file = new File(localFilePath);
            if (!file.exists()) {
                return retflag;
            }
            fileinputstream = new FileInputStream(file);
            final String filename = (fileNewName == null || "".equals(fileNewName)) ? file.getName() : fileNewName;
            this.sftpChannel.put(fileinputstream, filename);
            retflag = true;
            SftpUtil.log.info("\u4e0a\u4f20\u6587\u4ef6{}\u81f3\u76ee\u5f55{}\u6210\u529f", (Object)localFilePath, (Object)remoteDirectory);
        }
        catch (Exception e3) {
            SftpUtil.log.error("\u4e0a\u4f20\u6587\u4ef6{}\u81f3\u76ee\u5f55{}\u5931\u8d25", (Object)localFilePath, (Object)remoteDirectory);
            if (fileinputstream != null) {
                try {
                    fileinputstream.close();
                }
                catch (IOException e) {
                    SftpUtil.log.error("\u6587\u4ef6\u6d41\u5173\u95ed\u5931\u8d25,", (Throwable)e);
                }
            }
        }
        finally {
            if (fileinputstream != null) {
                try {
                    fileinputstream.close();
                }
                catch (IOException e2) {
                    SftpUtil.log.error("\u6587\u4ef6\u6d41\u5173\u95ed\u5931\u8d25,", (Throwable)e2);
                }
            }
        }
        return retflag;
    }
    
    public boolean download(final String directory, final String filename, final String saveDir, final String saveFileName) {
        boolean retflag = false;
        if (this.sftpChannel == null) {
            return retflag;
        }
        OutputStream fileinputstream = null;
        try {
            this.sftpChannel.cd(directory);
            String saveFilePath = null;
            if (saveDir.endsWith("/") || saveDir.endsWith("\\")) {
                saveFilePath = saveDir + saveFileName;
            }
            else {
                saveFilePath = saveDir + File.separator + saveFileName;
            }
            final File file = new File(saveFilePath);
            fileinputstream = new FileOutputStream(file);
            this.sftpChannel.get(filename, fileinputstream);
            retflag = true;
        }
        catch (SftpException e) {
            SftpUtil.log.error("sftp\u8fde\u63a5\u5931\u8d25,", (Throwable)e);
        }
        catch (FileNotFoundException e2) {
            SftpUtil.log.error("\u6587\u4ef6\u627e\u4e0d\u5230,", (Throwable)e2);
        }
        finally {
            if (fileinputstream != null) {
                try {
                    fileinputstream.close();
                }
                catch (IOException e3) {
                    SftpUtil.log.error("\u6587\u4ef6\u6d41\u5173\u95ed\u5931\u8d25,", (Throwable)e3);
                }
            }
        }
        return retflag;
    }
    
    private boolean downloadDir(final String directory, final String filename, final String saveDir, final String saveFileName) {
        boolean retflag = false;
        if (this.sftpChannel == null) {
            return retflag;
        }
        OutputStream fileinputstream = null;
        try {
            String saveFilePath = null;
            if (saveDir.endsWith("/") || saveDir.endsWith("\\")) {
                saveFilePath = saveDir + saveFileName;
            }
            else {
                saveFilePath = saveDir + File.separator + saveFileName;
            }
            final File file = new File(saveFilePath);
            fileinputstream = new FileOutputStream(file);
            this.sftpChannel.get(filename, fileinputstream);
            retflag = true;
        }
        catch (SftpException e) {
            SftpUtil.log.error("sftp\u8fde\u63a5\u5931\u8d25,", (Throwable)e);
        }
        catch (FileNotFoundException e2) {
            SftpUtil.log.error("\u6587\u4ef6\u627e\u4e0d\u5230,", (Throwable)e2);
        }
        finally {
            if (fileinputstream != null) {
                try {
                    fileinputstream.close();
                }
                catch (IOException e3) {
                    SftpUtil.log.error("\u6587\u4ef6\u6d41\u5173\u95ed\u5931\u8d25,", (Throwable)e3);
                }
            }
        }
        return retflag;
    }
    
    public boolean downloadDirectory(final String directory, final String saveDir) {
        boolean result = false;
        final List<String> fileNames = this.getFileList(directory);
        if (CollectionUtils.isEmpty(fileNames)) {
            return result;
        }
        for (final String fileName : fileNames) {
            result = this.downloadDir(directory, fileName, saveDir, fileName);
            if (!result) {
                result = this.downloadDir(directory, fileName, saveDir, fileName);
            }
        }
        return result;
    }
    
    public boolean downloadDirectory(final String directory, final String saveDir, final List<String> downFailFileNames) {
        boolean result = false;
        final List<String> fileNames = this.getFileList(directory);
        if (CollectionUtils.isEmpty(fileNames)) {
            return result;
        }
        for (final String fileName : fileNames) {
            result = this.downloadDir(directory, fileName, saveDir, fileName);
            if (!result) {
                downFailFileNames.add(fileName);
                result = true;
            }
        }
        return result;
    }
    
    public void closeServer() {
        if (this.sftpChannel != null) {
            this.sftpChannel.disconnect();
        }
        if (this.session != null) {
            this.session.disconnect();
        }
    }
    
    public ChannelSftp getSftpChannel() {
        return this.sftpChannel;
    }
    
    public static void main(final String[] args) {
        final SftpUtil sft = new SftpUtil("10.101.1.1", 22, "weblogic", "weblogic");
        sft.connectServer();
        sft.download("/home/weblogic/CRQ/tmp/ReportDownload/2015/20151118/", "2015111800000012.html", "d:\\", "2015111800000012.html");
        System.out.println(sft.isExists("/home/weblogic/ddd/ddd/dd/dd/dd/"));
        System.out.println(sft.mkdirs("/home/weblogic/ddd/ddd/dd/dd/dd/"));
        sft.closeServer();
    }
    
    static {
        log = LoggerFactory.getLogger((Class)SftpUtil.class);
    }
    
    public static class MyUserInfo implements UserInfo
    {
        private String passphrase;
        
        public MyUserInfo(final String passphrase) {
            this.passphrase = null;
            this.passphrase = passphrase;
        }
        
        public String getPassphrase() {
            return this.passphrase;
        }
        
        public String getPassword() {
            return null;
        }
        
        public boolean promptPassphrase(final String s) {
            return true;
        }
        
        public boolean promptPassword(final String s) {
            return true;
        }
        
        public boolean promptYesNo(final String s) {
            return true;
        }
        
        public void showMessage(final String s) {
            SftpUtil.log.info("sftp\u767b\u5f55\u4fe1\u606f{}", (Object)s);
        }
    }
}
